package top.fkxuexi.smartwork.core;

import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;

import java.io.*;
import java.util.Locale;

public class FreemarkerTemplateLoader implements TemplateLoader {


    private Configuration cfg;

    public FreemarkerTemplateLoader(Configuration cfg ){
        this.cfg = cfg;
    }

    @Override
    public Object findTemplateSource(String name) throws IOException {
        String languageTag = "_"+cfg.getLocale().toLanguageTag().replace("-","_");
        name = name.replace(languageTag,"");
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(name);
        if (in == null){
            in = this.getClass().getResourceAsStream(name);
        }
        byte[] b = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int len ;
        while ((len = in.read(b)) != -1){
            sb.append(new String(b,0,len));
        }
        System.out.println(sb.toString());
        Reader reader = new StringReader(sb.toString());
        return reader;
    }

    @Override
    public long getLastModified(Object templateSource) {
        return 0;
    }

    @Override
    public Reader getReader(Object templateSource, String encoding) throws IOException {
        return (Reader) templateSource;
    }

    @Override
    public void closeTemplateSource(Object templateSource) throws IOException {
        ((Reader)templateSource).close();
    }
}
